#coding:utf-8

import json
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from rest_framework.views import APIView
from API import models
from rest_framework.request import Request
from rest_framework import exceptions
from API.utils.premission import SVIPPremission,MyPremission
from rest_framework.parsers import JSONParser,FormParser
from rest_framework import serializers




ORDER_DICT = {
    1:{
        'name':'apple',
        'price':15
    },
    2:{
        'name':'dog',
        'price':100
    }
}


#生成md5 token校验码
def md5(user):
    import hashlib
    import time
    #当前时间，相当于生成一个随机的字符串
    ctime = str(time.time())
    m = hashlib.md5(bytes(user,encoding='utf-8'))
    m.update(bytes(ctime,encoding='utf-8'))
    return m.hexdigest()



class AuthView(APIView):
    '''用于用户登录验证'''
    authentication_classes = []    #由于设置了全局认证，所以在不需要认证的视图中配置空列表
    permission_classes = []        #同认证，权限也配置空列表
    def post(self,request,*args,**kwargs):
        ret = {'code':1000,'msg':None}

        try:
            #user = request._request.POST.get('username')

            #request.data 接收前端提交的json 数据
            user = request.data['username']
            #pwd = request._request.POST.get('password')
            pwd = request.data['password']

            obj = models.UserInfo.objects.filter(username=user,password=pwd).first()

            if not obj:
                ret['code'] = 1001

                ret['msg'] = '用户名或密码错误'

            #为用户创建token
            token = md5(user)

            #存在就更新，不存在就创建
            models.UserToken.objects.update_or_create(user=obj,defaults={'token':token})

            ret['token'] = token

        except Exception as e:
            ret['code'] = 1002
            ret['msg'] = '请求异常'

        return JsonResponse(ret)



class OrderView(APIView):
    '''
    订单相关业务(只有SVIP用户才能看)
    '''
    def get(self,request,*args,**kwargs):

        ret = {'code':1000,'msg':'30522d5d76a4e6dea68413e0ed02ed12','data':None}
        try:
            ret['data'] = ORDER_DICT
        except Exception as e:
            pass
        return JsonResponse(ret)




#要先写一个序列化的类
class RolesSerializer(serializers.Serializer):
    #Role表里面的字段id和title序列化
    id = serializers.IntegerField()
    title = serializers.CharField()


class RolesView(APIView):
    def get(self, request, *args, **kwargs):
        # 方式一：对于[obj,obj,obj]
        # （Queryset）
        roles = models.Role.objects.all()
        # 序列化，两个参数，instance:接受Queryset（或者对象）   mangy=True表示对Queryset进行处理，mant=False表示对对象进行进行处理
        ser = RolesSerializer(instance=roles, many=True)
        # 转成json格式，ensure_ascii=False表示显示中文，默认为True
        ret = json.dumps(ser.data, ensure_ascii=False)
        return HttpResponse(ret)



class UserInfoSerializer(serializers.ModelSerializer):
    group = serializers.HyperlinkedIdentityField(view_name='gp', lookup_field='group_id', lookup_url_kwarg='pk')
    class Meta:
        model = models.UserInfo
        #fields = "__all__"
        fields = ['id','username','password','group','roles']

        #表示连表的深度(序列化)
        depth = 0


class UserInfoView(APIView):
    '''用户的信息'''
    def get(self,request,*args,**kwargs):
        users = models.UserInfo.objects.all()
        #这里必须要传参数context={'request':request}
        ser = UserInfoSerializer(instance=users,many=True,context={'request':request})
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)


class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserGroup
        fields = "__all__"


class GroupView(APIView):
    def get(self,request,*args,**kwargs):
        pk = kwargs.get('pk')
        obj = models.UserGroup.objects.filter(pk=pk).first()

        ser = GroupSerializer(instance=obj,many=False)
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)




############### 对提交数据进行检验 ###############
class GroupValidation(object):
    def __init__(self,base):
        self.base = base

    def __call__(self, value):
        if not value.startswith(self.base):
            message = "标题必须以%s为开头"%self.base
            raise serializers.ValidationError(message)


class UserGroupSerializer(serializers.Serializer):
    title = serializers.CharField(validators=[GroupValidation('Test'),])


class UserGroupView(APIView):
    def post(self,request,*args, **kwargs):
        ser = UserGroupSerializer(data=request.data)
        if ser.is_valid():
            print(ser.validated_data['title'])
        else:
            print(ser.errors)

        return HttpResponse("用户提交数据验证")


##################################################分页###################################################

from API.utils.pager import PagerSerialiser
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination

# #自定义分页类1
# class MyPageNumberPagination(PageNumberPagination):
#     #每页显示多少个
#     page_size = 3
#     #默认每页显示3个，可以通过传入pager1/?page=2&size=4,改变默认每页显示的个数
#     page_size_query_param = "size"
#     #最大页数不超过10
#     max_page_size = 10
#     #获取页码数的
#     page_query_param = "page"

#自定义分页类2
class MyLimitOffsetPagination(LimitOffsetPagination):
    #默认显示的个数
    default_limit = 2
    #当前的位置
    offset_query_param = "offset"
    #通过limit改变默认显示的个数
    limit_query_param = "limit"
    #一页最多显示的个数
    max_limit = 10


#自定义分页类3 (加密分页)
class MyCursorPagination(CursorPagination):
    cursor_query_param = "cursor"
    page_size = 2     #每页显示2个数据
    ordering = 'id'   #排序
    page_size_query_param = None
    max_page_size = None


class Pager1View(APIView):
    def get(self,request,*args,**kwargs):
        #获取所有数据
        roles = models.Role.objects.all()
        #创建分页对象
        pg = MyCursorPagination()
        #获取分页的数据
        page_roles = pg.paginate_queryset(queryset=roles,request=request,view=self)
        #对数据进行序列化
        ser = PagerSerialiser(instance=page_roles,many=True)
        return Response(ser.data)
        # return pg.get_paginated_response(ser.data)